import sys

from deepseek_api_experience.model import client

class MessageManager:
    def __init__(self):
        self.messages = []

    def add_sys_message(self, message: str):
        self.messages.append({"role": "system", "content": message})

    def add_user_message(self, message: str):
        self.messages.append({"role": "user", "content": message})

    def add_ai_message(self, message: str):
        self.messages.append({"role": "assistant", "content": message})

    def get_messages(self):
        return self.messages
manager = MessageManager()

while True:
    try:
        user_input = input("User: ").strip()
        if user_input.lower() in ["quit", "exit", "q"]:
            print("Goodbye!")
            break

        print("AI: ", end="", flush=True)  # 确保"AI: "立即显示
        manager.add_user_message(user_input)
        # 流式调用API
        response_stream = client.chat.completions.create(
            model="deepseek-chat",
            messages=manager.get_messages(),
            stream=True,
            temperature=1.0,
            top_p=0.9,
        )

        full_response = []
        for chunk in response_stream:
            if chunk.choices and chunk.choices[0].delta.content:
                content = chunk.choices[0].delta.content
                print(content, end="", flush=True)  # 逐字打印
                full_response.append(content)
        manager.add_ai_message("".join(full_response))
        print()  # 换行

    except KeyboardInterrupt:
        print("\nInterrupted by user")
        break

    except Exception as e:
        print(f"\nError: {str(e)}", file=sys.stderr)
        continue